import asyncio
import logging
import os
import queue
import random
import re
import string
import threading

from aiogram import types
from aiogram.dispatcher import FSMContext
from aiogram.dispatcher.filters.state import State, StatesGroup
from aiogram.types import ParseMode
from PIL import Image

import client
import client_kb
from create_bot import BASE_DIR, dp

from . import es_country_menu
from .generate import (
    generate_dni_number,
    generate_EQUIPO_number,
    generate_name,
    generate_number_doc,
    process_generate_signature,
    process_passport_photo,
)
from .utils import country_nationality_to_code

logger = logging.getLogger(__name__)


class IDGenerateState(StatesGroup):
    """Статусы опроса пользователя для генерации паспорта."""

    doc_type_select = State()
    bill_id_input = State()
    bill_client_id = State()
    client_last_name = State()
    client_first_name = State()
    client_birth_date = State()
    client_doc_number = State()
    client_can_number = State()
    client_dni_number = State()
    client_equipo_number = State()
    client_nationality = State()
    client_address = State()
    client_city_residence = State()
    client_provinces_residence = State()
    client_provinces_birth = State()
    client_country_residence = State()
    client_sex = State()
    client_parents = State()
    client_validity = State()
    client_emission_date = State()
    client_photo = State()
    client_signature_id = State()
    client_hologram = State()
    size = State()
    start_generate = State()
    edit_data = State()


# словарь с данными, которые запрашиваем у пользователя
data_fields = [
    {"title": "Имя", "key": "client_first_name"},
    {"title": "Фамилия", "key": "client_last_name"},
    {"title": "Дата рождения", "key": "client_birth_date"},
    {"title": "Номер документа", "key": "client_doc_number"},
    {"title": "CAN номер", "key": "client_can_number"},
    {"title": "Номер DNI", "key": "client_dni_number"},
    {"title": "Номер EQUIPO", "key": "client_equipo_number"},
    {"title": "Национальность", "key": "client_nationality"},
    {"title": "Улица проживания и номер дома", "key": "client_address"},
    {"title": "Город проживания", "key": "client_city_residence"},
    {"title": "Провинция проживания", "key": "client_provinces_residence"},
    {"title": "Провинция рождения", "key": "client_provinces_birth"},
    {"title": "Страна проживания", "key": "client_country_residence"},
    {"title": "Пол", "key": "client_sex"},
    {"title": "Родители", "key": "client_parents"},
    {"title": "Срок действия", "key": "client_validity"},
    {"title": "Дата выдачи", "key": "client_emission_date"},
    {"title": "Фотография", "key": "client_photo"},
    {"title": "Подпись", "key": "client_signature_id"},
    {"title": "Голограмма", "key": "client_hologram"},
    {"title": "Размер документа", "key": "size"},
]


async def data_checkup(user_id: int, state: FSMContext):
    """Формирование прогресса заполнения анкеты."""

    try:
        data = await state.get_data()
        checkup_text = "Данные клиента:\n"
        for field in data_fields:
            if field["key"] in data:
                checkup_text += f"✅{field['title']}: {data[field['key']]}\n"
            else:
                checkup_text += f"{field['title']}:\n"
        if "message_to_edit_id" in data:
            await dp.bot.delete_message(
                chat_id=user_id, message_id=data["message_to_edit_id"]
            )
        return (await dp.bot.send_message(chat_id=user_id, text=checkup_text))[
            "message_id"
        ]
    except:
        pass


async def delete_user_reply(user_id: int, message_id: int):
    """Удаление предыдущих сообщений."""
    try:
        await dp.bot.delete_message(chat_id=user_id, message_id=message_id)
    except Exception as e:
        logger.warning(f"Unable to delete user message: {e}")


async def id_client_first_name_input(message: types.Message, state: FSMContext):
    """Начало опроса, запрос имени."""

    message_to_edit_id = await data_checkup(message.from_user.id, state)
    await state.update_data(message_to_edit_id=message_to_edit_id)

    question_message_id = (
        await message.answer(
            "Введите имя✏️\n",
            parse_mode=ParseMode.HTML,
            reply_markup=client_kb.es_back_kb,
        )
    )["message_id"]

    logger.info(
        f"Пользователь {message.from_user.username} начал заполнение анкеты на ID Испании."
    )
    await state.update_data(question_message_id=question_message_id)
    await IDGenerateState.client_first_name.set()


@dp.message_handler(
    lambda message: "◀️Назад" not in message.text,
    state=IDGenerateState.client_first_name,
)
async def id_client_first_name_valid(message: types.Message, state: FSMContext):
    """Проверка введённой имени на валидность."""
    client_first_name = None
    await delete_user_reply(message.from_user.id, message.message_id)
    data = await state.get_data()

    if "question_message_id" in data:
        await dp.bot.delete_message(
            chat_id=message.from_user.id, message_id=data["question_message_id"]
        )
    else:
        logger.warning("question_message_id not found in state data")

    if re.match("^[A-Za-z `]+$", message.text) is not None:
        client_first_name = message.text
    if client_first_name is None:
        message_to_edit_id = await data_checkup(message.from_user.id, state)
        await state.update_data(message_to_edit_id=message_to_edit_id)
        question_message_id = (
            await message.answer(
                text="❌Введите имя в правильном формате.\n"
                "<i>Формат ввода: только латинские буквы.</i>",
                parse_mode=ParseMode.HTML,
            )
        )["message_id"]
        await state.update_data(question_message_id=question_message_id)
    else:
        await state.update_data(client_first_name=client_first_name.upper())
        if "edit_mode" in data:
            return await start_generate_edit(message.from_user.id, state)
        message_to_edit_id = await data_checkup(message.from_user.id, state)
        await state.update_data(message_to_edit_id=message_to_edit_id)
        await id_client_last_name_input(message, state)


async def id_client_last_name_input(message: types.Message, state: FSMContext):
    """Запрос фамилии."""
    message_to_edit_id = await data_checkup(message.from_user.id, state)
    await state.update_data(message_to_edit_id=message_to_edit_id)
    question_message_id = (
        await message.answer(
            "Введите фамилию✏️",
            parse_mode=ParseMode.HTML,
            reply_markup=client_kb.es_back_kb,
        )
    )["message_id"]
    await state.update_data(question_message_id=question_message_id)
    await IDGenerateState.client_last_name.set()


@dp.message_handler(
    lambda message: "◀️Назад" not in message.text,
    state=IDGenerateState.client_last_name,
)
async def id_client_last_name_valid(message: types.Message, state: FSMContext):
    """Проверка введённого фамилии на валидность."""
    client_last_name = None
    await delete_user_reply(message.from_user.id, message.message_id)
    data = await state.get_data()

    if "question_message_id" in data:
        await dp.bot.delete_message(
            chat_id=message.from_user.id, message_id=data["question_message_id"]
        )
    else:
        logger.warning("question_message_id not found in state data")

    if re.match("^[A-Za-z `]+$", message.text) is not None:
        client_last_name = message.text
    if client_last_name is None:
        message_to_edit_id = await data_checkup(message.from_user.id, state)
        await state.update_data(message_to_edit_id=message_to_edit_id)
        question_message_id = (
            await message.answer(
                text="❌Введите фамилию в правильном формате.\n"
                "<i>Формат ввода: только латинские буквы.</i>",
                parse_mode=ParseMode.HTML,
            )
        )["message_id"]
        await state.update_data(question_message_id=question_message_id)
    else:
        await state.update_data(client_last_name=client_last_name.upper())
        if "edit_mode" in data:
            return await start_generate_edit(message.from_user.id, state)
        message_to_edit_id = await data_checkup(message.from_user.id, state)
        await state.update_data(message_to_edit_id=message_to_edit_id)
        await id_client_birth_date_input(message, state)


async def id_client_birth_date_input(message: types.Message, state: FSMContext):
    """Запрос даты рождения."""
    message_to_edit_id = await data_checkup(message.from_user.id, state)
    await state.update_data(message_to_edit_id=message_to_edit_id)
    question_message_id = (
        await message.answer(
            "Введите дату рождения✏️",
            parse_mode=ParseMode.HTML,
            reply_markup=client_kb.es_back_kb,
        )
    )["message_id"]
    await state.update_data(question_message_id=question_message_id)
    await IDGenerateState.client_birth_date.set()


@dp.message_handler(
    lambda message: "◀️Назад" not in message.text,
    state=IDGenerateState.client_birth_date,
)
async def id_client_birth_date_valid(message: types.Message, state: FSMContext):
    """Проверка введённой даты рождения на валидность."""
    client_birth_date = None
    await delete_user_reply(message.from_user.id, message.message_id)
    data = await state.get_data()

    if "question_message_id" in data:
        await dp.bot.delete_message(
            chat_id=message.from_user.id, message_id=data["question_message_id"]
        )
    else:
        logger.warning("question_message_id not found in state data")

    if re.match("^\d{2}.\d{2}.\d{4}$", message.text) is not None:
        client_birth_date = message.text
    if client_birth_date is None:
        message_to_edit_id = await data_checkup(message.from_user.id, state)
        await state.update_data(message_to_edit_id=message_to_edit_id)
        question_message_id = (
            await message.answer(
                text="❌Введите дату рождения в правильном формате.\n"
                "<i>Формат ввода: дд.мм.гггг.</i>",
                parse_mode=ParseMode.HTML,
            )
        )["message_id"]
        await state.update_data(question_message_id=question_message_id)
    else:
        await state.update_data(client_birth_date=client_birth_date.upper())
        if "edit_mode" in data:
            return await start_generate_edit(message.from_user.id, state)
        message_to_edit_id = await data_checkup(message.from_user.id, state)
        await state.update_data(message_to_edit_id=message_to_edit_id)
        await id_client_doc_number_input(message, state)


async def id_client_doc_number_input(message: types.Message, state: FSMContext):
    """Запрос номера документа."""
    message_to_edit_id = await data_checkup(message.from_user.id, state)
    await state.update_data(message_to_edit_id=message_to_edit_id)
    question_message_id = (
        await message.answer(
            text="Введите номер документа✏️\n"
            "<i>Формат ввода: XXxxxxxx</i>\n"
            "<i>XX-рандомные буквы, xxxxxx-рандомные цифры</i>\n",
            reply_markup=client_kb.es_generate_number,
        )
    )["message_id"]
    await state.update_data(question_message_id=question_message_id)
    await IDGenerateState.client_doc_number.set()


@dp.message_handler(
    lambda message: "◀️Назад" not in message.text,
    state=IDGenerateState.client_doc_number,
)
async def id_client_doc_number_valid(message: types.Message, state: FSMContext):
    """Проверка введённой номера документа."""
    client_doc_number = None
    await delete_user_reply(message.from_user.id, message.message_id)
    data = await state.get_data()

    if "question_message_id" in data:
        await dp.bot.delete_message(
            chat_id=message.from_user.id, message_id=data["question_message_id"]
        )
    else:
        logger.warning("question_message_id not found in state data")

    if message.text == "Сгенерировать":
        client_doc_number = generate_number_doc()
    if re.match("^[A-Z]{2}\d{6}$", message.text) is not None:
        client_doc_number = "B" + message.text
    if client_doc_number is None:
        message_to_edit_id = await data_checkup(message.from_user.id, state)
        await state.update_data(message_to_edit_id=message_to_edit_id)
        question_message_id = (
            await message.answer(
                text="❌Введите номер документа в правильном формате.\n"
                "<i>Формат ввода: XXxxxxxx</i>\n"
                "<i>XX-рандомные буквы, xxxxxx-рандомные цифры</i>\n",
                parse_mode=ParseMode.HTML,
                reply_markup=client_kb.es_generate_number,
            )
        )["message_id"]
        await state.update_data(question_message_id=question_message_id)
    else:
        await state.update_data(client_doc_number=client_doc_number.upper())
        if "edit_mode" in data:
            return await start_generate_edit(message.from_user.id, state)
        message_to_edit_id = await data_checkup(message.from_user.id, state)
        await state.update_data(message_to_edit_id=message_to_edit_id)
        await id_client_can_number_input(message, state)


async def id_client_can_number_input(message: types.Message, state: FSMContext):
    """Запрос CAN номера."""
    message_to_edit_id = await data_checkup(message.from_user.id, state)
    await state.update_data(message_to_edit_id=message_to_edit_id)
    question_message_id = (
        await message.answer(
            "Введите CAN номер✏️\n" "<i>Формат ввода: 6 цифр.</i>",
            parse_mode=ParseMode.HTML,
            reply_markup=client_kb.es_generate_number,
        )
    )["message_id"]
    await state.update_data(question_message_id=question_message_id)
    await IDGenerateState.client_can_number.set()


@dp.message_handler(
    lambda message: "◀️Назад" not in message.text,
    state=IDGenerateState.client_can_number,
)
async def id_client_can_number_valid(message: types.Message, state: FSMContext):
    """Проверка введённого CAN номера на валидность."""
    client_can_number = None
    await delete_user_reply(message.from_user.id, message.message_id)
    data = await state.get_data()

    if "question_message_id" in data:
        await dp.bot.delete_message(
            chat_id=message.from_user.id, message_id=data["question_message_id"]
        )
    else:
        logger.warning("question_message_id not found in state data")

    if message.text == "Сгенерировать":
        client_can_number = "".join(random.choice(string.digits) for _ in range(6))
    if re.match("^\d{6}$", message.text) is not None:
        client_can_number = message.text
    if client_can_number is None:
        message_to_edit_id = await data_checkup(message.from_user.id, state)
        await state.update_data(message_to_edit_id=message_to_edit_id)
        question_message_id = (
            await message.answer(
                text="❌Введите CAN номер в правильном формате.\n"
                "<i>Формат ввода: 6 цифр.</i>",
                parse_mode=ParseMode.HTML,
            )
        )["message_id"]
        await state.update_data(question_message_id=question_message_id)
    else:
        await state.update_data(client_can_number=client_can_number.upper())
        if "edit_mode" in data:
            return await start_generate_edit(message.from_user.id, state)
        message_to_edit_id = await data_checkup(message.from_user.id, state)
        await state.update_data(message_to_edit_id=message_to_edit_id)
        await id_client_dni_number_input(message, state)


async def id_client_dni_number_input(message: types.Message, state: FSMContext):
    """Запрос DNI номера."""
    message_to_edit_id = await data_checkup(message.from_user.id, state)
    await state.update_data(message_to_edit_id=message_to_edit_id)
    question_message_id = (
        await message.answer(
            "Введите DNI номер✏️\n" "<i>Формат ввода: 8 цифр, 1 буква</i>",
            parse_mode=ParseMode.HTML,
            reply_markup=client_kb.es_generate_number,
        )
    )["message_id"]
    await state.update_data(question_message_id=question_message_id)
    await IDGenerateState.client_dni_number.set()


@dp.message_handler(
    lambda message: "◀️Назад" not in message.text,
    state=IDGenerateState.client_dni_number,
)
async def id_client_dni_number_valid(message: types.Message, state: FSMContext):
    """Проверка введённого DNI номера на валидность."""
    client_dni_number = None
    await delete_user_reply(message.from_user.id, message.message_id)
    data = await state.get_data()

    if "question_message_id" in data:
        await dp.bot.delete_message(
            chat_id=message.from_user.id, message_id=data["question_message_id"]
        )
    else:
        logger.warning("question_message_id not found in state data")

    if message.text == "Сгенерировать":
        client_dni_number = generate_dni_number()
    if re.match("^\d{8}[A-Z]{1}$", message.text.upper()) is not None:
        client_dni_number = message.text
    if client_dni_number is None:
        message_to_edit_id = await data_checkup(message.from_user.id, state)
        await state.update_data(message_to_edit_id=message_to_edit_id)
        question_message_id = (
            await message.answer(
                text="❌Введите DNI номер в правильном формате.\n"
                "<i>Формат ввода: 8 цифр, 1 буква</i>",
                parse_mode=ParseMode.HTML,
            )
        )["message_id"]
        await state.update_data(question_message_id=question_message_id)
    else:
        await state.update_data(client_dni_number=client_dni_number.upper())
        if "edit_mode" in data:
            return await start_generate_edit(message.from_user.id, state)
        message_to_edit_id = await data_checkup(message.from_user.id, state)
        await state.update_data(message_to_edit_id=message_to_edit_id)
        await id_client_equipo_number_input(message, state)


async def id_client_equipo_number_input(message: types.Message, state: FSMContext):
    """Запрос номера EQUIPO."""
    message_to_edit_id = await data_checkup(message.from_user.id, state)
    await state.update_data(message_to_edit_id=message_to_edit_id)
    question_message_id = (
        await message.answer(
            "Введите номер EQUIPO✏️\n" "<i>Пример: 12345R6R7.</i>",
            parse_mode=ParseMode.HTML,
            reply_markup=client_kb.es_generate_number,
        )
    )["message_id"]
    await state.update_data(question_message_id=question_message_id)
    await IDGenerateState.client_equipo_number.set()


@dp.message_handler(
    lambda message: "◀️Назад" not in message.text,
    state=IDGenerateState.client_equipo_number,
)
async def id_client_equipo_number_valid(message: types.Message, state: FSMContext):
    """Проверка введённого номера EQUIPO на валидность."""
    client_equipo_number = None
    await delete_user_reply(message.from_user.id, message.message_id)
    data = await state.get_data()

    if "question_message_id" in data:
        await dp.bot.delete_message(
            chat_id=message.from_user.id, message_id=data["question_message_id"]
        )
    else:
        logger.warning("question_message_id not found in state data")
    if message.text == "Сгенерировать":
        client_equipo_number = generate_EQUIPO_number()
    if re.match("^\d{5}[A-Z]\d[A-Z]\d$", message.text) is not None:
        client_equipo_number = message.text
    if client_equipo_number is None:
        message_to_edit_id = await data_checkup(message.from_user.id, state)
        await state.update_data(message_to_edit_id=message_to_edit_id)
        question_message_id = (
            await message.answer(
                text="❌Введите номер EQUIPO в правильном формате.\n"
                "<i>Формат ввода: пример - 12345R6R7.</i>",
                parse_mode=ParseMode.HTML,
            )
        )["message_id"]
        await state.update_data(question_message_id=question_message_id)
    else:
        await state.update_data(client_equipo_number=client_equipo_number.upper())
        if "edit_mode" in data:
            return await start_generate_edit(message.from_user.id, state)
        message_to_edit_id = await data_checkup(message.from_user.id, state)
        await state.update_data(message_to_edit_id=message_to_edit_id)
        await id_client_nationality_input(message, state)


async def id_client_nationality_input(message: types.Message, state: FSMContext):
    """Запрос национальности."""
    message_to_edit_id = await data_checkup(message.from_user.id, state)
    await state.update_data(message_to_edit_id=message_to_edit_id)
    question_message_id = (
        await message.answer(
            "Введите национальность в виде кода страны,\n"
            "либо выберите по умолчанию✏️\n"
            "Формат кода: ISO-3166.\n",
            parse_mode=ParseMode.HTML,
            reply_markup=client_kb.es_national_number,
        )
    )["message_id"]
    await state.update_data(question_message_id=question_message_id)
    await IDGenerateState.client_nationality.set()


@dp.message_handler(
    lambda message: "◀️Назад" not in message.text,
    state=IDGenerateState.client_nationality,
)
async def id_client_nationality_valid(message: types.Message, state: FSMContext):
    """Проверка введённой национальности на валидность."""
    client_nationality = None
    await delete_user_reply(message.from_user.id, message.message_id)
    data = await state.get_data()

    if "question_message_id" in data:
        await dp.bot.delete_message(
            chat_id=message.from_user.id, message_id=data["question_message_id"]
        )
    else:
        logger.warning("question_message_id not found in state data")
    if message.text == "ESP":
        client_nationality = "ESP"
    if message.text.upper() in country_nationality_to_code:
        client_nationality = message.text
    if client_nationality is None:
        message_to_edit_id = await data_checkup(message.from_user.id, state)
        await state.update_data(message_to_edit_id=message_to_edit_id)
        question_message_id = (
            await message.answer(
                text="❌Введите национальность в правильном формате.\n"
                "<i>Формат кода: ISO-3166.</i>",
                parse_mode=ParseMode.HTML,
            )
        )["message_id"]
        await state.update_data(question_message_id=question_message_id)
    else:
        await state.update_data(client_nationality=client_nationality.upper())
        if "edit_mode" in data:
            return await start_generate_edit(message.from_user.id, state)
        message_to_edit_id = await data_checkup(message.from_user.id, state)
        await state.update_data(message_to_edit_id=message_to_edit_id)
        await id_client_address_input(message, state)


async def id_client_address_input(message: types.Message, state: FSMContext):
    """Запрос адреса проживания."""
    message_to_edit_id = await data_checkup(message.from_user.id, state)
    await state.update_data(message_to_edit_id=message_to_edit_id)
    question_message_id = (
        await message.answer(
            "Введите улицу и номер дома проживания✏️",
            parse_mode=ParseMode.HTML,
            reply_markup=client_kb.es_back_kb,
        )
    )["message_id"]
    await state.update_data(question_message_id=question_message_id)
    await IDGenerateState.client_address.set()


@dp.message_handler(
    lambda message: "◀️Назад" not in message.text, state=IDGenerateState.client_address
)
async def id_client_address_valid(message: types.Message, state: FSMContext):
    """Проверка введённого адреса на валидность."""
    client_address = None
    await delete_user_reply(message.from_user.id, message.message_id)
    data = await state.get_data()

    if "question_message_id" in data:
        await dp.bot.delete_message(
            chat_id=message.from_user.id, message_id=data["question_message_id"]
        )
    else:
        logger.warning("question_message_id not found in state data")

    if re.match("^[A-Za-z `]+\d+$", message.text) is not None:
        client_address = message.text
    if client_address is None:
        message_to_edit_id = await data_checkup(message.from_user.id, state)
        await state.update_data(message_to_edit_id=message_to_edit_id)
        question_message_id = (
            await message.answer(
                text="❌Введите адрес проживания в правильном формате.\n"
                "<i>Формат ввода: только латинские буквы и цифры.</i>",
                parse_mode=ParseMode.HTML,
            )
        )["message_id"]
        await state.update_data(question_message_id=question_message_id)
    else:
        await state.update_data(client_address=client_address.upper())
        if "edit_mode" in data:
            return await start_generate_edit(message.from_user.id, state)
        message_to_edit_id = await data_checkup(message.from_user.id, state)
        await state.update_data(message_to_edit_id=message_to_edit_id)
        await id_client_city_residence_input(message, state)


async def id_client_city_residence_input(message: types.Message, state: FSMContext):
    """Запрос города проживания."""
    message_to_edit_id = await data_checkup(message.from_user.id, state)
    await state.update_data(message_to_edit_id=message_to_edit_id)
    question_message_id = (
        await message.answer(
            "Введите город проживания✏️",
            parse_mode=ParseMode.HTML,
            reply_markup=client_kb.es_back_kb,
        )
    )["message_id"]
    await state.update_data(question_message_id=question_message_id)
    await IDGenerateState.client_city_residence.set()


@dp.message_handler(
    lambda message: "◀️Назад" not in message.text,
    state=IDGenerateState.client_city_residence,
)
async def id_client_city_residence_valid(message: types.Message, state: FSMContext):
    """Проверка введённого города проживания на валидность."""
    client_city_residence = None
    await delete_user_reply(message.from_user.id, message.message_id)
    data = await state.get_data()

    if "question_message_id" in data:
        await dp.bot.delete_message(
            chat_id=message.from_user.id, message_id=data["question_message_id"]
        )
    else:
        logger.warning("question_message_id not found in state data")

    if re.match("^[A-Za-z `]+$", message.text) is not None:
        client_city_residence = message.text
    if client_city_residence is None:
        message_to_edit_id = await data_checkup(message.from_user.id, state)
        await state.update_data(message_to_edit_id=message_to_edit_id)
        question_message_id = (
            await message.answer(
                text="❌Введите город проживания в правильном формате.\n"
                "<i>Формат ввода: только латинские буквы.</i>",
                parse_mode=ParseMode.HTML,
            )
        )["message_id"]
        await state.update_data(question_message_id=question_message_id)
    else:
        await state.update_data(client_city_residence=client_city_residence.upper())
        if "edit_mode" in data:
            return await start_generate_edit(message.from_user.id, state)
        message_to_edit_id = await data_checkup(message.from_user.id, state)
        await state.update_data(message_to_edit_id=message_to_edit_id)
        await id_client_provinces_residence_input(message, state)


async def id_client_provinces_residence_input(
    message: types.Message, state: FSMContext
):
    """Запрос провинции проживания."""
    message_to_edit_id = await data_checkup(message.from_user.id, state)
    await state.update_data(message_to_edit_id=message_to_edit_id)
    question_message_id = (
        await message.answer(
            "Введите провинцию проживания✏️",
            parse_mode=ParseMode.HTML,
            reply_markup=client_kb.es_back_kb,
        )
    )["message_id"]
    await state.update_data(question_message_id=question_message_id)
    await IDGenerateState.client_provinces_residence.set()


@dp.message_handler(
    lambda message: "◀️Назад" not in message.text,
    state=IDGenerateState.client_provinces_residence,
)
async def id_client_provinces_residence_valid(
    message: types.Message, state: FSMContext
):
    """Проверка введённого провинции проживания на валидность."""
    client_provinces_residence = None
    await delete_user_reply(message.from_user.id, message.message_id)
    data = await state.get_data()

    if "question_message_id" in data:
        await dp.bot.delete_message(
            chat_id=message.from_user.id, message_id=data["question_message_id"]
        )
    else:
        logger.warning("question_message_id not found in state data")

    if re.match("^[A-Za-z `]+$", message.text) is not None:
        client_provinces_residence = message.text
    if client_provinces_residence is None:
        message_to_edit_id = await data_checkup(message.from_user.id, state)
        await state.update_data(message_to_edit_id=message_to_edit_id)
        question_message_id = (
            await message.answer(
                text="❌Введите провинцию проживания в правильном формате.\n"
                "<i>Формат ввода: только латинские буквы.</i>",
                parse_mode=ParseMode.HTML,
            )
        )["message_id"]
        await state.update_data(question_message_id=question_message_id)
    else:
        await state.update_data(
            client_provinces_residence=client_provinces_residence.upper()
        )
        if "edit_mode" in data:
            return await start_generate_edit(message.from_user.id, state)
        message_to_edit_id = await data_checkup(message.from_user.id, state)
        await state.update_data(message_to_edit_id=message_to_edit_id)
        await id_client_provinces_birth_input(message, state)


async def id_client_provinces_birth_input(message: types.Message, state: FSMContext):
    """Запрос провинции рождения."""
    message_to_edit_id = await data_checkup(message.from_user.id, state)
    await state.update_data(message_to_edit_id=message_to_edit_id)
    question_message_id = (
        await message.answer(
            "Введите провинцию рождения✏️",
            parse_mode=ParseMode.HTML,
            reply_markup=client_kb.es_back_kb,
        )
    )["message_id"]
    await state.update_data(question_message_id=question_message_id)
    await IDGenerateState.client_provinces_birth.set()


@dp.message_handler(
    lambda message: "◀️Назад" not in message.text,
    state=IDGenerateState.client_provinces_birth,
)
async def id_client_provinces_birth_valid(message: types.Message, state: FSMContext):
    """Проверка введённого провинции рождения на валидность."""
    client_provinces_birth = None
    await delete_user_reply(message.from_user.id, message.message_id)
    data = await state.get_data()

    if "question_message_id" in data:
        await dp.bot.delete_message(
            chat_id=message.from_user.id, message_id=data["question_message_id"]
        )
    else:
        logger.warning("question_message_id not found in state data")

    if re.match("^[A-Za-z `]+$", message.text) is not None:
        client_provinces_birth = message.text
    if client_provinces_birth is None:
        message_to_edit_id = await data_checkup(message.from_user.id, state)
        await state.update_data(message_to_edit_id=message_to_edit_id)
        question_message_id = (
            await message.answer(
                text="❌Введите провинцию рождения в правильном формате.\n"
                "<i>Формат ввода: только латинские буквы.</i>",
                parse_mode=ParseMode.HTML,
            )
        )["message_id"]
        await state.update_data(question_message_id=question_message_id)
    else:
        await state.update_data(client_provinces_birth=client_provinces_birth.upper())
        if "edit_mode" in data:
            return await start_generate_edit(message.from_user.id, state)
        message_to_edit_id = await data_checkup(message.from_user.id, state)
        await state.update_data(message_to_edit_id=message_to_edit_id)
        await id_client_country_residence_input(message, state)


async def id_client_country_residence_input(message: types.Message, state: FSMContext):
    """Запрос страны проживания."""
    message_to_edit_id = await data_checkup(message.from_user.id, state)
    await state.update_data(message_to_edit_id=message_to_edit_id)
    question_message_id = (
        await message.answer(
            "Введите страну проживания✏️",
            parse_mode=ParseMode.HTML,
            reply_markup=client_kb.es_country,
        )
    )["message_id"]
    await state.update_data(question_message_id=question_message_id)
    await IDGenerateState.client_country_residence.set()


@dp.message_handler(
    lambda message: "◀️Назад" not in message.text,
    state=IDGenerateState.client_country_residence,
)
async def id_client_country_residence_valid(message: types.Message, state: FSMContext):
    """Проверка введённого страны проживания на валидность."""
    client_country_residence = None
    await delete_user_reply(message.from_user.id, message.message_id)
    data = await state.get_data()

    if "question_message_id" in data:
        await dp.bot.delete_message(
            chat_id=message.from_user.id, message_id=data["question_message_id"]
        )
    else:
        logger.warning("question_message_id not found in state data")
    if message.text == "España":
        client_country_residence = "España"
    if re.match("^[A-Za-z `]+$", message.text) is not None:
        client_country_residence = message.text
    if client_country_residence is None:
        message_to_edit_id = await data_checkup(message.from_user.id, state)
        await state.update_data(message_to_edit_id=message_to_edit_id)
        question_message_id = (
            await message.answer(
                text="❌Введите страну проживания в правильном формате.\n"
                "<i>Формат ввода: только латинские буквы.</i>",
                parse_mode=ParseMode.HTML,
            )
        )["message_id"]
        await state.update_data(question_message_id=question_message_id)
    else:
        await state.update_data(
            client_country_residence=client_country_residence.upper()
        )
        if "edit_mode" in data:
            return await start_generate_edit(message.from_user.id, state)
        message_to_edit_id = await data_checkup(message.from_user.id, state)
        await state.update_data(message_to_edit_id=message_to_edit_id)
        await id_client_sex_input(message, state)


async def id_client_sex_input(message: types.Message, state: FSMContext):
    """Запрос пола."""
    message_to_edit_id = await data_checkup(message.from_user.id, state)
    await state.update_data(message_to_edit_id=message_to_edit_id)
    question_message_id = (
        await message.answer(
            "Выберите пол✏️",
            parse_mode=ParseMode.HTML,
            reply_markup=client_kb.kb_es_pass_gender,
        )
    )["message_id"]
    await state.update_data(question_message_id=question_message_id)
    await IDGenerateState.client_sex.set()


@dp.message_handler(
    lambda message: "◀️Назад" not in message.text, state=IDGenerateState.client_sex
)
async def id_client_sex_valid(message: types.Message, state: FSMContext):
    """Сохранение пола."""
    client_sex = None
    await delete_user_reply(message.from_user.id, message.message_id)
    data = await state.get_data()

    if "question_message_id" in data:
        await dp.bot.delete_message(
            chat_id=message.from_user.id, message_id=data["question_message_id"]
        )
    else:
        logger.warning("question_message_id not found in state data")

    if message.text == "Мужской 🙎🏻‍♂️":
        client_sex = "M"
    elif message.text == "Женский 🙍🏻‍♀️":
        client_sex = "F"
    else:
        message_to_edit_id = await data_checkup(message.from_user.id, state)
        await state.update_data(message_to_edit_id=message_to_edit_id)
        question_message_id = (
            await message.answer(
                text="❌Выберите пол через клавиатуру.\n",
                parse_mode=ParseMode.HTML,
                reply_markup=client_kb.kb_es_pass_gender,
            )
        )["message_id"]
        return await state.update_data(question_message_id=question_message_id)
    await state.update_data(client_sex=client_sex)
    if "edit_mode" in data:
        return await start_generate_edit(message.from_user.id, state)
    message_to_edit_id = await data_checkup(message.from_user.id, state)
    await state.update_data(message_to_edit_id=message_to_edit_id)
    await id_client_parents_input(message, state)


async def id_client_parents_input(message: types.Message, state: FSMContext):
    """Запрос информации о родителях."""
    message_to_edit_id = await data_checkup(message.from_user.id, state)
    await state.update_data(message_to_edit_id=message_to_edit_id)
    question_message_id = (
        await message.answer(
            "Введите родителей в формате✏️\n"
            "<i>snamedad namedad / snamemom namemom</i>",
            parse_mode=ParseMode.HTML,
            reply_markup=client_kb.es_generate_number,
        )
    )["message_id"]
    await state.update_data(question_message_id=question_message_id)
    await IDGenerateState.client_parents.set()


@dp.message_handler(
    lambda message: "◀️Назад" not in message.text, state=IDGenerateState.client_parents
)
async def id_client_parents_valid(message: types.Message, state: FSMContext):
    """Проверка введённого информации о родителях на валидность."""
    client_parents = None
    await delete_user_reply(message.from_user.id, message.message_id)
    data = await state.get_data()
    client_nationality = data["client_nationality"]
    parents = message.text.split("/")

    if "question_message_id" in data:
        await dp.bot.delete_message(
            chat_id=message.from_user.id, message_id=data["question_message_id"]
        )
    else:
        logger.warning("question_message_id not found in state data")
    if message.text == "Сгенерировать":
        client_parents = generate_name(
            code_country=country_nationality_to_code[client_nationality].lower()
        )
    if (
        len(parents) == 2
        and len(parents[0].split()) > 1
        and len(parents[1].split()) > 1
    ):
        client_parents = message.text
    if client_parents is None:
        message_to_edit_id = await data_checkup(message.from_user.id, state)
        await state.update_data(message_to_edit_id=message_to_edit_id)
        question_message_id = (
            await message.answer(
                text="❌Введите информацию о родителях в правильном формате.\n"
                "<i>Формат ввода: snamedad namedad / snamemom namemom</i>",
                parse_mode=ParseMode.HTML,
            )
        )["message_id"]
        await state.update_data(question_message_id=question_message_id)
    else:
        await state.update_data(client_parents=client_parents.upper())
        if "edit_mode" in data:
            return await start_generate_edit(message.from_user.id, state)
        message_to_edit_id = await data_checkup(message.from_user.id, state)
        await state.update_data(message_to_edit_id=message_to_edit_id)
        await id_client_validity_input(message, state)


async def id_client_validity_input(message: types.Message, state: FSMContext):
    """Запрос срока действия карты."""
    message_to_edit_id = await data_checkup(message.from_user.id, state)
    await state.update_data(message_to_edit_id=message_to_edit_id)
    question_message_id = (
        await message.answer(
            "Выберите длительность действия ID карты✏️\n",
            parse_mode=ParseMode.HTML,
            reply_markup=client_kb.es_validity_id,
        )
    )["message_id"]
    await state.update_data(question_message_id=question_message_id)
    await IDGenerateState.client_validity.set()


@dp.message_handler(
    lambda message: "◀️Назад" not in message.text, state=IDGenerateState.client_validity
)
async def id_client_validity_valid(message: types.Message, state: FSMContext):
    """Сохранения выбранного срока действия карты."""
    client_validity = None
    await delete_user_reply(message.from_user.id, message.message_id)
    data = await state.get_data()

    if "question_message_id" in data:
        await dp.bot.delete_message(
            chat_id=message.from_user.id, message_id=data["question_message_id"]
        )
    else:
        logger.warning("question_message_id not found in state data")

    if message.text == "5 лет":
        client_validity = "5 лет"
    elif message.text == "10 лет":
        client_validity = "10 лет️"
    else:
        message_to_edit_id = await data_checkup(message.from_user.id, state)
        await state.update_data(message_to_edit_id=message_to_edit_id)
        question_message_id = (
            await message.answer(
                text="❌Выберите срок действия через клавиатуру.\n",
                parse_mode=ParseMode.HTML,
                reply_markup=client_kb.es_validity_id,
            )
        )["message_id"]
        return await state.update_data(question_message_id=question_message_id)

    await state.update_data(client_validity=client_validity)
    if "edit_mode" in data:
        return await start_generate_edit(message.from_user.id, state)
    message_to_edit_id = await data_checkup(message.from_user.id, state)
    await state.update_data(message_to_edit_id=message_to_edit_id)
    await id_client_emission_date_input(message, state)


async def id_client_emission_date_input(message: types.Message, state: FSMContext):
    """Запрос даты выдачи."""
    message_to_edit_id = await data_checkup(message.from_user.id, state)
    await state.update_data(message_to_edit_id=message_to_edit_id)
    question_message_id = (
        await message.answer(
            "Введите дату выдачи✏️\n",
            parse_mode=ParseMode.HTML,
            reply_markup=client_kb.es_back_kb,
        )
    )["message_id"]
    await state.update_data(question_message_id=question_message_id)
    await IDGenerateState.client_emission_date.set()


@dp.message_handler(
    lambda message: "◀️Назад" not in message.text,
    state=IDGenerateState.client_emission_date,
)
async def id_client_emission_date_valid(message: types.Message, state: FSMContext):
    """Проверка даты выдачи."""
    client_emission_date = None
    await delete_user_reply(message.from_user.id, message.message_id)
    data = await state.get_data()

    if "question_message_id" in data:
        await dp.bot.delete_message(
            chat_id=message.from_user.id, message_id=data["question_message_id"]
        )
    else:
        logger.warning("question_message_id not found in state data")

    if re.match("^\d{2}.\d{2}.\d{4}$", message.text) is not None:
        client_emission_date = message.text
    if client_emission_date is None:
        message_to_edit_id = await data_checkup(message.from_user.id, state)
        await state.update_data(message_to_edit_id=message_to_edit_id)
        question_message_id = (
            await message.answer(
                text="❌Введите дату выдачи в правильном формате.\n"
                "<i>Формат ввода: дд.мм.гггг.</i>",
                parse_mode=ParseMode.HTML,
                reply_markup=client_kb.es_generate_number,
            )
        )["message_id"]
        await state.update_data(question_message_id=question_message_id)
    else:
        await state.update_data(client_emission_date=client_emission_date)
        if "edit_mode" in data:
            return await start_generate_edit(message.from_user.id, state)
        message_to_edit_id = await data_checkup(message.from_user.id, state)
        await state.update_data(message_to_edit_id=message_to_edit_id)
        await id_client_photo_input(message, state)


async def id_client_photo_input(message: types.Message, state: FSMContext):
    """Запрос фотографии."""
    message_to_edit_id = await data_checkup(message.from_user.id, state)
    await state.update_data(message_to_edit_id=message_to_edit_id)
    question_message_id = (
        await message.answer(
            text="Загрузите фотографию\n"
            "❗️Требования к фотографии:\n"
            "➖ На фото должен быть вырезан фон\n"
            "➖ Фотография должна быть загружена без сжатия , "
            "нажимаем скрепку - файл - выбрать фото\n"
            "➖ На фотографии должно быть видно плечи, глаза открыты\n"
            "➖ Кадр должен быть в хорошем освещении\n"
            "➖ Лицо должно быть под прямым углом к камере\n"
            "❗️ Поддерживаемый формат: PNG❗️",
            reply_markup=client_kb.es_back_kb,
        )
    )["message_id"]
    await state.update_data(question_message_id=question_message_id)
    await IDGenerateState.client_photo.set()


@dp.message_handler(
    content_types=types.ContentType.DOCUMENT, state=IDGenerateState.client_photo
)
async def id_client_photo_valid(message: types.Message, state: FSMContext):
    """Проверка загруженной фотографии на соответствие."""
    data = await state.get_data()
    # Проверить, есть ли в сообщении документ.
    # Проверить, находится ли документ в требуемом формате (PNG).
    file_info = await dp.bot.get_file(message.document.file_id)
    await message.delete()
    if file_info.file_path.lower().endswith(".png"):
        # Загрузите документ и сохраните его как user_id.png.
        photo_path = f"./files/es/photo_usr/{message.from_user.id}.png"
        await dp.bot.download_file(file_info.file_path, photo_path)
        # Проверьте, есть ли у изображения альфа-канал
        img = Image.open(photo_path).convert("RGBA")
        if img.mode == "RGBA":
            # Обработайте фото в отдельной теме
            thread = threading.Thread(
                target=process_passport_photo, args=(message.from_user.id,)
            )
            thread.start()
            # Проверка состояния потока каждую секунду с использованием asyncio.sleep
            while thread.is_alive():
                await asyncio.sleep(1)
            # Проверить, существует ли обработанное фото
            processed_photo_path = f"./files/es/photo_usr/{message.from_user.id}_w.png"
            if os.path.exists(processed_photo_path) or message.text == "◀️Назад":
                question_message_id = data.get("question_message_id")
                await state.update_data(user_id=message.from_user.id)
                await state.update_data(client_photo="VERIFIED")
                try:
                    await dp.bot.delete_message(
                        chat_id=message.chat.id, message_id=question_message_id
                    )
                    message_to_edit_id = await data_checkup(message.from_user.id, state)
                    await state.update_data(message_to_edit_id=message_to_edit_id)
                except:
                    pass
                await id_client_signature_id_input(message, state)

            else:
                await dp.bot.send_message(
                    chat_id=message.chat.id,
                    text="❌ Фотография не соответствует требованиям.\n"
                    "ИИ не смог обработать вашу фотографию.\n"
                    "Это происходит, если фото не соответствует требованиям, "
                    "проверьте что расширение файла PNG, "
                    "либо загрузите другое изображение.",
                )
        else:
            await dp.bot.send_message(
                chat_id=message.chat.id,
                text="❌ Фотография не соответствует требованиям.\n"
                "ИИ не смог обработать вашу фотографию.\n"
                "Это происходит, если фото не соответствует требованиям, "
                "проверьте что расширение файла PNG, "
                "либо загрузите другое изображение.",
            )
    else:
        await dp.bot.send_message(
            chat_id=message.chat.id,
            text="❌ Фотография не соответствует требованиям.\n"
            "ИИ не смог обработать вашу фотографию.\n"
            "Это происходит, если фото не соответствует требованиям, "
            "проверьте что расширение файла PNG, "
            "либо загрузите другое изображение.",
        )


@dp.message_handler(
    lambda message: "◀️Назад" not in message.text, state=IDGenerateState.client_photo
)
async def process_photo_non_type(message: types.Message, state: FSMContext):
    await message.delete()
    message_delete = await message.answer(
        "Вы должны отправить фотографию без фона в формате PNG и без сжатия.",
        reply_markup=client_kb.es_back_kb,
    )
    await asyncio.sleep(4)
    await message_delete.delete()


@dp.message_handler(
    content_types=types.ContentType.PHOTO, state=IDGenerateState.client_photo
)
async def process_photo_non_type_photo(message: types.Message, state: FSMContext):
    await message.delete()
    message_delete = await message.answer(
        "Вы должны отправить фотографию без фона в формате PNG и без сжатия.",
        reply_markup=client_kb.es_back_kb,
    )
    await asyncio.sleep(4)
    await message_delete.delete()


async def id_client_signature_id_input(message: types.Message, state: FSMContext):
    """Генерация подписи и предложение на выбор."""
    data = await state.get_data()
    message_to_edit_id = await data_checkup(message.from_user.id, state)
    await state.update_data(message_to_edit_id=message_to_edit_id)

    process_generate_signature(
        user_id=message.from_user.id, data=data["client_last_name"].split()[0]
    )

    kb = types.InlineKeyboardMarkup()
    kb.add(
        types.InlineKeyboardButton(text="1", callback_data="sig_1"),
        types.InlineKeyboardButton(text="2", callback_data="sig_2"),
        types.InlineKeyboardButton(text="3", callback_data="sig_3"),
    )
    kb.add(
        types.InlineKeyboardButton(text="4", callback_data="sig_4"),
        types.InlineKeyboardButton(text="5", callback_data="sig_5"),
        types.InlineKeyboardButton(text="6", callback_data="sig_6"),
    )
    kb.add(types.InlineKeyboardButton(text="Не ставить", callback_data="sig_0"))
    kb.add(types.InlineKeyboardButton(text="◀️Назад", callback_data="◀️Назад"))

    photo_path = f"./files/es/photo_usr/{message.from_user.id}_choose_signature.png"  # Замените на путь к вашей картинке
    with open(photo_path, "rb") as photo:
        question_message_id = (
            await dp.bot.send_photo(
                chat_id=message.from_user.id,
                photo=photo,
                caption="Выберите тип подписи:",
                reply_markup=kb,
            )
        )["message_id"]
    await state.update_data(question_message_id=question_message_id)
    await IDGenerateState.client_signature_id.set()


@dp.callback_query_handler(
    lambda c: c.data.startswith("sig_") and "◀️Назад" not in c.data,
    state=IDGenerateState.client_signature_id,
)
async def id_client_signature_id_valid(
    callback_query: types.CallbackQuery, state: FSMContext
):
    """Сохраняет выбор подписи."""
    await dp.bot.answer_callback_query(callback_query.id)
    signature_id = int(callback_query.data.split("_")[1])
    await state.update_data(client_signature_id=signature_id)
    logger.info(f"Пользователь {callback_query.from_user.username} выбрал подпись.")

    data = await state.get_data()
    if "question_message_id" in data:
        await dp.bot.delete_message(
            chat_id=callback_query.from_user.id, message_id=data["question_message_id"]
        )
    else:
        logger.warning("question_message_id not found in state data")

    if "edit_mode" in data:
        return await start_generate_edit(callback_query.from_user.id, state)
    message_to_edit_id = await data_checkup(callback_query.from_user.id, state)
    await state.update_data(message_to_edit_id=message_to_edit_id)
    await id_client_hologram_input(callback_query, state)


async def id_client_hologram_input(message: types.Message, state: FSMContext):
    """Голограммы на выбор."""
    message_to_edit_id = await data_checkup(message.from_user.id, state)
    await state.update_data(message_to_edit_id=message_to_edit_id)

    kb = types.InlineKeyboardMarkup()
    kb.add(
        types.InlineKeyboardButton(text="1", callback_data="holo_1"),
        types.InlineKeyboardButton(text="2", callback_data="holo_2"),
        types.InlineKeyboardButton(text="3", callback_data="holo_3"),
    )
    kb.add(types.InlineKeyboardButton(text="Не ставить", callback_data="holo_0"))
    kb.add(types.InlineKeyboardButton(text="◀️Назад", callback_data="◀️Назад"))

    photo_path = f"./files/es/es_id/all_holo.png"  # Замените на путь к вашей картинке
    with open(photo_path, "rb") as photo:
        question_message_id = (
            await dp.bot.send_photo(
                chat_id=message.from_user.id,
                photo=photo,
                caption="Выберите тип голограммы:",
                reply_markup=kb,
            )
        )["message_id"]
    await state.update_data(question_message_id=question_message_id)
    await IDGenerateState.client_hologram.set()


@dp.callback_query_handler(
    lambda c: c.data.startswith("holo_") and "◀️Назад" not in c.data,
    state=IDGenerateState.client_hologram,
)
async def id_client_hologram_valid(
    callback_query: types.CallbackQuery, state: FSMContext
):
    """Сохраняет выбор голограммы."""
    await dp.bot.answer_callback_query(callback_query.id)
    client_hologram = int(callback_query.data.split("_")[1])
    logger.info(f"Пользователь {callback_query.from_user.id} выбрал голограмму")
    await state.update_data(client_hologram=client_hologram)

    data = await state.get_data()
    if "question_message_id" in data:
        await dp.bot.delete_message(
            chat_id=callback_query.from_user.id, message_id=data["question_message_id"]
        )
    else:
        logger.warning("question_message_id not found in state data")
    if "edit_mode" in data:
        return await start_generate_edit(callback_query.from_user.id, state)
    message_to_edit_id = await data_checkup(callback_query.from_user.id, state)
    await state.update_data(message_to_edit_id=message_to_edit_id)
    await id_size_input(callback_query, state)


async def id_size_input(callback_query: types.CallbackQuery, state: FSMContext):
    """Запрашивает размер документа."""
    message_to_edit_id = await data_checkup(callback_query.from_user.id, state)
    await state.update_data(message_to_edit_id=message_to_edit_id)
    question_message_id = (
        await dp.bot.send_message(
            chat_id=callback_query.from_user.id,
            text="Выберите размер документа",
            reply_markup=client_kb.es_size,
        )
    )["message_id"]
    await state.update_data(question_message_id=question_message_id)
    await IDGenerateState.size.set()


@dp.message_handler(
    lambda message: "◀️Назад" not in message.text, state=IDGenerateState.size
)
async def id_start_generate(message: types.Message, state: FSMContext):
    """Сохранение выбранного формата документа и отправление в генерацию документа."""
    if message.text == "📃На листе А4":
        size_type = "A4"
    elif message.text == "🪪В размер документа":
        size_type = "DOC"
    else:
        message_to_edit_id = await data_checkup(message.from_user.id, state)
        await state.update_data(message_to_edit_id=message_to_edit_id)
        kb = types.ReplyKeyboardMarkup(resize_keyboard=True)
        kb.add(types.KeyboardButton(text="📃На листе А4"))
        kb.add(types.KeyboardButton(text="🪪В размер документа"))
        question_message_id = (
            await message.answer(
                text="❌Выберите тип через клавиатуру.\n",
                parse_mode=ParseMode.HTML,
                reply_markup=kb,
            )
        )["message_id"]
        return await state.update_data(question_message_id=question_message_id)
    await message.delete()
    await state.update_data(size=size_type)
    logger.info(f"Пользователь {message.from_user.id} выбрал размер документа")
    data = await state.get_data()
    if "question_message_id" in data:
        await dp.bot.delete_message(
            chat_id=message.from_user.id, message_id=data["question_message_id"]
        )
    else:
        logger.warning("question_message_id not found in state data")
    if "edit_mode" in data:
        return await start_generate_edit(message.from_user.id, state)
    message_to_edit_id = await data_checkup(message.from_user.id, state)
    await state.update_data(message_to_edit_id=message_to_edit_id)
    await start_generate(message, state)


state_input_functions = {
    "IDGenerateState:client_last_name": id_client_first_name_input,
    "IDGenerateState:client_birth_date": id_client_last_name_input,
    "IDGenerateState:client_doc_number": id_client_birth_date_input,
    "IDGenerateState:client_can_number": id_client_doc_number_input,
    "IDGenerateState:client_dni_number": id_client_can_number_input,
    "IDGenerateState:client_equipo_number": id_client_dni_number_input,
    "IDGenerateState:client_nationality": id_client_equipo_number_input,
    "IDGenerateState:client_address": id_client_nationality_input,
    "IDGenerateState:client_city_residence": id_client_address_input,
    "IDGenerateState:client_provinces_residence": id_client_city_residence_input,
    "IDGenerateState:client_provinces_birth": id_client_provinces_residence_input,
    "IDGenerateState:client_country_residence": id_client_provinces_birth_input,
    "IDGenerateState:client_sex": id_client_country_residence_input,
    "IDGenerateState:client_parents": id_client_sex_input,
    "IDGenerateState:client_validity": id_client_parents_input,
    "IDGenerateState:client_emission_date": id_client_validity_input,
    "IDGenerateState:client_photo": id_client_emission_date_input,
    "IDGenerateState:client_signature_id": id_client_photo_input,
    "IDGenerateState:client_hologram": id_client_signature_id_input,
    "IDGenerateState:size": id_client_hologram_input,
}


@dp.message_handler(lambda message: message.text == "◀️Назад", state=IDGenerateState)
async def go_back(message: types.Message, state: FSMContext):
    """Функция реагирующая на кнопку назад."""

    current_state = str(await state.get_state())
    if current_state == "IDGenerateState:client_first_name":
        await es_country_menu.create_spain(message)
    else:
        if current_state in state_input_functions:
            input_function = state_input_functions[current_state]
            await input_function(
                message, state
            )  # вызов функции ввода для предыдущего состояния
        else:
            await message.answer("Unknown state.")


@dp.callback_query_handler(lambda call: call.data == "◀️Назад", state=IDGenerateState)
async def go_back(call: types.CallbackQuery, state: FSMContext):
    """Функция реагирующая на кнопку назад."""

    await call.message.delete()
    current_state = str(await state.get_state())
    if current_state == "IDGenerateState:client_first_name":
        await es_country_menu.create_spain(call.message)
    else:
        if current_state in state_input_functions:
            input_function = state_input_functions[current_state]
            await input_function(
                call.message, state
            )  # вызов функции ввода для предыдущего состояния
        else:
            await call.message.answer("Unknown state.")


@dp.message_handler(state=IDGenerateState.start_generate)
async def start_generate(message: types.Message, state: FSMContext):
    """Начало генерации документа."""
    message_to_delete = await message.answer("Ожидайте, генерируется...")
    data = await state.get_data()
    try:
        await dp.bot.delete_message(
            chat_id=message.from_user.id, message=data["message_to_edit_id"]
        )
    except:
        pass
    result_queue = queue.Queue()
    bill_thread = threading.Thread(
        target=generate_id, args=(data, message.from_user.id, result_queue)
    )
    bill_thread.start()
    bill_thread.join()
    result = result_queue.get()
    if "Error" in result:
        await message.answer("❌Ошибка при генерации изображения")
        logger.info(f"Ошибка при генерации изображения,\n - {result}")
    else:
        await dp.bot.delete_message(
            chat_id=message.from_user.id, message_id=message_to_delete["message_id"]
        )
        with open(result + "_wm.png", "rb") as photo:
            await dp.bot.send_document(chat_id=message.from_user.id, document=photo)
            await message.answer(
                "Завершите покупку документа.", reply_markup=client_kb.kb_es_finish_id
            )


async def start_generate_edit(user_id: int, state: FSMContext):
    message_to_delete = await dp.bot.send_message(
        chat_id=user_id, text="Ожидайте генерируется..."
    )
    data = await state.get_data()
    result_queue = queue.Queue()
    id_thread = threading.Thread(target=generate_id, args=(data, user_id, result_queue))
    id_thread.start()
    id_thread.join()
    result = result_queue.get()
    if "Error" in result:
        await dp.bot.send_message(
            chat_id=user_id, text="❌Ошибка при генерации изображения"
        )
    else:
        await dp.bot.delete_message(
            chat_id=user_id, message_id=message_to_delete["message_id"]
        )
        with open(result + "_wm.png", "rb") as photo:
            await dp.bot.send_document(chat_id=user_id, document=photo)
            await dp.bot.send_message(
                chat_id=user_id,
                text="Завершите покупку документа.",
                reply_markup=client_kb.kb_es_finish_id,
            )


@dp.callback_query_handler(text="es_change_id", state="*")
async def es_change_id(call: types.CallbackQuery, state: FSMContext):
    kb = types.ReplyKeyboardMarkup(one_time_keyboard=True)
    await call.message.delete()
    for field in data_fields:
        kb.add(types.KeyboardButton(text=f'{field["title"]}'))
    question_message_id = (
        await call.message.answer(
            text="Выберите параметр, который хотите изменить", reply_markup=kb
        )
    )["message_id"]
    await state.update_data(question_message_id=question_message_id)
    await IDGenerateState.edit_data.set()


@dp.message_handler(state=IDGenerateState.edit_data)
async def edit_field(message: types.Message, state: FSMContext):
    key = None
    for field in data_fields:
        if field["title"] == message.text:
            key = field["key"]
    if key is None:
        return await message.answer("❌Выберите параметр через клавиатуру")
    await state.update_data(edit_mode=1)
    func_name = key
    func_name_with_input = "id_" + func_name + "_input"

    # Получаем ссылку на функцию с использованием имени и вызываем ее
    function_to_call = globals()[func_name_with_input]
    await function_to_call(message, state)


@dp.callback_query_handler(text="es_pay_id", state="*")
async def command_pay_es_id(callback: types.CallbackQuery, state: FSMContext):
    await state.finish()
    await state.update_data(pay_country="es_id")
    await client.command_promo_quest(callback, state)


@dp.callback_query_handler(text="es_exit_id", state="*")
async def command_pay_exit(callback: types.CallbackQuery, state: FSMContext):
    if callback.message.text == "es_exit_id":
        await state.finish()


def generate_id(data, user_id, result_queue):
    try:
        import datetime
        import random

        import codicefiscale as codicefiscale
        from PIL import Image, ImageDraw, ImageEnhance, ImageFilter, ImageFont

        def multiply_images(image1, image2):
            if image1.size != image2.size:
                print("Изображения должны быть одного размера")
                return None

            result_image = Image.new("RGBA", image1.size, (0, 0, 0, 0))
            for x in range(image1.width):
                for y in range(image1.height):
                    pixel1 = image1.getpixel((x, y))
                    pixel2 = image2.getpixel((x, y))
                    new_pixel = tuple(int(a * b / 255) for a, b in zip(pixel1, pixel2))
                    result_image.putpixel((x, y), new_pixel)

            return result_image

        # Загрузка исходного изображения
        front = Image.open(f"./files/es/es_id/spain_id_front.png").convert("RGBA")
        back = Image.open(f"./files/es/es_id/spain_id_back.png").convert("RGBA")
        """
        Переменные текста
        """
        last_name = data["client_last_name"]
        first_name = data["client_first_name"]
        birth_date = data["client_birth_date"]
        doc_number = data["client_doc_number"]
        can_number = data["client_can_number"]
        dni_number = data["client_dni_number"]
        equipo_number = data["client_equipo_number"]
        nationality = data["client_nationality"]
        address = data["client_address"]
        city_residence = data["client_city_residence"]
        provinces_residence = data["client_provinces_residence"]
        provinces_birth = data["client_provinces_birth"]
        country_residence = data["client_country_residence"]
        sex = data["client_sex"]
        parents = data["client_parents"]
        validity = data["client_validity"].split()[0]
        emission_date = data["client_emission_date"]
        signature_id = data["client_signature_id"]
        hologram = data["client_hologram"]
        size = data["size"]

        # дата окончания паспорта
        expire_date_year = datetime.datetime.strftime(
            datetime.datetime.strptime(emission_date, "%d.%m.%Y")
            + datetime.timedelta(days=365 * int(validity)),
            "%d %m %Y",
        )

        """Отрисовка фронтальной части."""
        # Создание объекта ImageDraw для рисования на изображении
        txt_front = Image.new("RGBA", front.size, (255, 255, 255, 0))
        go_txt = ImageDraw.Draw(txt_front)
        font = ImageFont.truetype(f"./fonts/OCRB Regular.ttf", 32)

        # Рендер фамилии
        x, y = 399, 200
        go_txt.text(
            xy=(x, y),
            text=last_name.split()[0],
            font=font,
            fill=(0, 0, 0, 235),
            stroke_width=0,
            anchor="lm",
        )
        if len(last_name.split()) == 2:
            x, y = 399, 229
            go_txt.text(
                xy=(x, y),
                text=last_name.split()[1],
                font=font,
                fill=(0, 0, 0, 235),
                stroke_width=0,
                anchor="lm",
            )
        # Рендер имени
        x, y = 399, 289
        go_txt.text(
            xy=(x, y),
            text=first_name,
            font=font,
            fill=(0, 0, 0, 235),
            stroke_width=0,
            anchor="lm",
        )
        # Рендер пола
        x, y = 399, 349
        go_txt.text(
            xy=(x, y),
            text=sex,
            font=font,
            fill=(0, 0, 0, 235),
            stroke_width=0,
            anchor="lm",
        )
        # Рендер национальности
        x, y = 544, 349
        go_txt.text(
            xy=(x, y),
            text=nationality,
            font=font,
            fill=(0, 0, 0, 235),
            stroke_width=0,
            anchor="lm",
        )
        # Рендер дня рождения
        x, y = 403, 417
        go_txt.text(
            xy=(x, y),
            text=" ".join(birth_date.split(".")),
            font=font,
            fill=(0, 0, 0, 235),
            stroke_width=0,
            anchor="lm",
        )
        # Рендер id номера
        x, y = 399, 465
        go_txt.text(
            xy=(x, y),
            text=doc_number,
            font=font,
            fill=(0, 0, 0, 235),
            stroke_width=0,
            anchor="lm",
        )
        # Рендер маленького id номера
        font_id = ImageFont.truetype(f"./fonts/OCRB Regular.ttf", 17)
        x, y = 795, 125
        go_txt.text(
            xy=(x, y),
            text=doc_number,
            font=font_id,
            fill=(0, 0, 0, 235),
            stroke_width=0,
            anchor="lm",
        )
        # Рендер срока действия документа
        x, y = 582, 465
        go_txt.text(
            xy=(x, y),
            text=expire_date_year,
            font=font,
            fill=(0, 0, 0, 235),
            stroke_width=0,
            anchor="lm",
        )
        # Рендер DNI
        font_dni = ImageFont.truetype(f"./fonts/es_OCR-B 10 BT.ttf", 50)
        x, y = 100, 587
        go_txt.text(
            xy=(x, y),
            text=dni_number,
            font=font_dni,
            fill=(0, 0, 0, 235),
            stroke_width=0,
            anchor="lm",
        )
        # Рендер CAN
        font_can = ImageFont.truetype(f"./fonts/es_OCR-B 10 BT.ttf", 45)
        x, y = 809, 553
        go_txt.text(
            xy=(x, y),
            text=can_number,
            font=font_can,
            fill=(0, 0, 0, 235),
            stroke_width=0,
            anchor="lm",
        )

        """
        Вставка маленькой фотографии
        """
        # Откройте другое изображение
        overlay_image = Image.open(f"./files/es/photo_usr/{user_id}_w.png").convert(
            "LA"
        )
        # Изменение прозрачности
        alpha_value = 125
        alpha = overlay_image.getchannel("A").point(lambda i: i * alpha_value / 255)
        overlay_image.putalpha(alpha)
        # Измените размер verlay_image
        new_size = (70, 89)  # Замените width и height на нужные значения
        overlay_image = overlay_image.resize(new_size, Image.LANCZOS)

        overlay_position = (
            836,
            343,
        )  # координаты x, y для вставки обрезанного изображения

        # Вставьте overlay_image на image с использованием альфа-канала
        front.paste(overlay_image, overlay_position, overlay_image)

        # Рендер даты выдачи
        font_emission = ImageFont.truetype(f"./fonts/es_OCR-B 10 BT.ttf", 30)
        x, y = 809, 400
        go_txt.text(
            xy=(x, y),
            text="".join([sym[0:2] for sym in emission_date.split(".")]),
            font=font_emission,
            fill=(86, 86, 86, 150),
            stroke_width=0,
            anchor="lm",
        )

        txt_blur = txt_front.filter(ImageFilter.GaussianBlur(radius=0.4))
        front = Image.alpha_composite(front, txt_blur)

        # Генерация и рендер подписи
        if signature_id != 0:
            fonts_dict = {
                1: ImageFont.truetype(f"./fonts/1.ttf", size=220),
                2: ImageFont.truetype(f"./fonts/2.ttf", size=125),
                3: ImageFont.truetype(f"./fonts/3.ttf", size=145),
                4: ImageFont.truetype(f"./fonts/4.ttf", size=100),
                5: ImageFont.truetype(f"./fonts/5.ttf", size=150),
                6: ImageFont.truetype(f"./fonts/6.ttf", size=150),
                7: ImageFont.truetype(f"./fonts/66.ttf", size=100),
            }
            if signature_id == 6:
                font = fonts_dict[5]
                x, y = 445, 546
                txt = Image.new("RGBA", front.size, (255, 255, 255, 0))
                go_txt = ImageDraw.Draw(txt)
                go_txt.text(
                    xy=(x, y),
                    text=f"{last_name.split()[0].capitalize()}",
                    font=font,
                    fill=(0, 0, 0, 250),
                    stroke_width=-1,
                    anchor="lm",
                )
                fnt66 = ImageFont.truetype(f"./fonts/66.ttf", size=100)
                go_txt.text(
                    xy=(x + 75, y - 15), text=f"k", font=fonts_dict[7], fill="#000000"
                )
                txt_blur = txt.filter(ImageFilter.GaussianBlur(radius=1.0))
                # Создайте новый слой подписи с размером, соответствующим изображению документа
                signature_layer = Image.new("RGBA", front.size, (255, 255, 255, 0))
                # Вставьте изображение подписи на слой подписи
                signature_position = (0, 0)  # координаты x, y для вставки подписи
                signature_layer.paste(txt_blur, signature_position)
                # Объедините изображение документа и слой подписи
                front = Image.alpha_composite(front, signature_layer)
            else:
                font = fonts_dict[signature_id]
                x, y = 445, 546
                txt = Image.new("RGBA", front.size, (255, 255, 255, 0))
                go_txt = ImageDraw.Draw(txt)
                go_txt.text(
                    xy=(x, y),
                    text=f"{last_name.split()[0].capitalize()}",
                    font=font,
                    fill=(22, 22, 22, 235),
                    stroke_width=-1,
                    anchor="lm",
                )
                txt_blur = txt.filter(ImageFilter.GaussianBlur(radius=1.0))
                # Создайте новый слой подписи с размером, соответствующим изображению документа
                signature_layer = Image.new("RGBA", front.size, (255, 255, 255, 0))
                # Вставьте изображение подписи на слой подписи
                signature_position = (0, 0)  # координаты x, y для вставки подписи
                signature_layer.paste(txt_blur, signature_position)
                # Объедините изображение документа и слой подписи
                front = Image.alpha_composite(front, signature_layer)

        """
        Вставка фотографии
        """
        # Откройте другое изображение
        overlay_image = Image.open(f"./files/es/photo_usr/{user_id}_w.png").convert(
            "LA"
        )
        # Изменение прозрачности
        alpha_value = 250
        alpha = overlay_image.getchannel("A").point(lambda i: i * alpha_value / 255)
        overlay_image.putalpha(alpha)
        # Измените размер
        new_size = (361, 432)  # Замените width и height на нужные значения
        overlay_image = overlay_image.resize(new_size, Image.LANCZOS)
        overlay_position = (
            24,
            122,
        )  # координаты x, y для вставки обрезанного изображения
        overlay_layer = Image.new("RGBA", front.size, (255, 255, 255, 0))
        overlay_layer.paste(overlay_image, overlay_position, overlay_image)
        # Используйте функцию multiply_images() для наложения overlay_image на image
        overlay_layer = multiply_images(front, overlay_layer)
        # Объедините исходное изображение и новый слой с помощью `Image.alpha_composite()`
        front = Image.alpha_composite(front, overlay_layer)

        """
        Вставка голограммы на фотографию
        """
        if hologram != 0:
            overlay_image = Image.open(f"./files/es/es_id/holo{hologram}.png").convert(
                "RGBA"
            )
            # Измените размер overlay_image
            new_size = (287, 336)  # Замените width и height на нужные значения
            overlay_image = overlay_image.resize(new_size, Image.LANCZOS)
            # Изменение прозрачности
            alpha_value = 210
            alpha = overlay_image.getchannel("A").point(lambda i: i * alpha_value / 255)
            overlay_image.putalpha(alpha)
            # Задайте координаты для вставки overlay_image на image
            overlay_position = (228, 249)  # Замените x и y на нужные значения координат
            # Вставьте overlay_image на image с использованием альфа-канала
            image = Image.new("RGBA", front.size, "white")
            image.paste(overlay_image, overlay_position, overlay_image)
            image = multiply_images(front, image)
            front = Image.alpha_composite(front, image)

        """Отрисовка бэковой части."""
        txt_back = Image.new("RGBA", back.size, (255, 255, 255, 0))
        go_txt = ImageDraw.Draw(txt_back)
        font = ImageFont.truetype(f"./fonts/OCRB Regular.ttf", 32)

        # Рендер адреса проживания
        x, y = 39, 58
        go_txt.text(
            xy=(x, y),
            text=address,
            font=font,
            fill=(22, 22, 22, 235),
            stroke_width=0,
            anchor="lm",
        )
        # Рендер маленького id номера
        font_id = ImageFont.truetype(f"./fonts/OCRB Regular.ttf", 17)
        x, y = 224, 125
        go_txt.text(
            xy=(x, y),
            text=doc_number[::-1],
            font=font_id,
            fill=(0, 0, 0, 255),
            stroke_width=0,
            anchor="rm",
        )
        # Рендер города проживания
        x, y = 285, 96
        go_txt.text(
            xy=(x, y),
            text=city_residence,
            font=font,
            fill=(22, 22, 22, 235),
            stroke_width=0,
            anchor="lm",
        )
        # Рендер провинции проживания
        x, y = 285, 124
        go_txt.text(
            xy=(x, y),
            text=provinces_residence,
            font=font,
            fill=(22, 22, 22, 235),
            stroke_width=0,
            anchor="lm",
        )
        # # Рендер страны проживания
        # x, y = 407, 170
        # go_txt.text(
        #     xy=(x, y),
        #     text=country_residence,
        #     font=font,
        #     fill=(22, 22, 22, 235),
        #     stroke_width=0,
        #     anchor="lm",
        # )
        # Рендер места рождения проживания
        x, y = 285, 232
        go_txt.text(
            xy=(x, y),
            text=provinces_birth.split()[0],
            font=font,
            fill=(22, 22, 22, 235),
            stroke_width=0,
            anchor="lm",
        )
        if len(provinces_birth.split()) == 2:
            x, y = 285, 261
            go_txt.text(
                xy=(x, y),
                text=provinces_birth.split()[1],
                font=font,
                fill=(22, 22, 22, 235),
                stroke_width=0,
                anchor="lm",
            )
        # Рендер данных о родителях
        if len(parents) > 35:
            father, mather = parents.split("/")
            x, y = 285, 349
            go_txt.text(
                xy=(x, y),
                text=f"{father}/",
                font=font,
                fill=(22, 22, 22, 235),
                stroke_width=0,
                anchor="lm",
            )
            x, y = 285, 381
            go_txt.text(
                xy=(x, y),
                text=mather,
                font=font,
                fill=(22, 22, 22, 235),
                stroke_width=0,
                anchor="lm",
            )
        else:
            x, y = 285, 349
            go_txt.text(
                xy=(x, y),
                text=parents,
                font=font,
                fill=(22, 22, 22, 235),
                stroke_width=0,
                anchor="lm",
            )
        # Рендер equipo
        font_v = ImageFont.truetype(f"./fonts/OCRB Regular.ttf", 29)
        txt_v = Image.new("L", size=(160, 25))
        ImageDraw.Draw(txt_v).text((0, 0), equipo_number, fill=255, font=font_v)

        txt_v = txt_v.rotate(90, resample=Image.BICUBIC, expand=True).filter(
            ImageFilter.GaussianBlur(radius=0.4)
        )
        back.paste((22, 22, 22, 235), box=(45, 184), mask=txt_v)

        # Рендер кода внизу паспорта
        def name_string(name: str) -> str:
            """Функция определяющая кол-во слов в строке, и разбивающая её символом."""
            if len(name) > 1:
                return "<".join(name.split())
            else:
                return name

        font_number = ImageFont.truetype(f"./fonts/OCRB Regular.ttf", 49)
        text = ""
        # количество символов в строке
        amount_symbols = 30
        # контрольная цифра
        digits = str(random.choice(string.digits))
        # первая строка
        first_string = f"ID{nationality}{doc_number}{digits}{dni_number}"
        diff_first = amount_symbols - len(first_string)
        text += f'{first_string + "<" * diff_first}\n'
        # вторая строка
        d_birth, m_birth, y_birth = [sym[-2::] for sym in birth_date.split(".")]
        d_expire, m_expire, y_expire = [sym[-2::] for sym in expire_date_year.split()]
        two_string = (
            f"{y_birth}{m_birth}{d_birth}{digits}"
            f"{sex}{y_expire}{m_expire}{d_expire}{digits}{nationality}"
        )
        diff_two = amount_symbols - len(two_string) - 1
        text += f'{two_string + "<" * diff_two}{digits}\n'
        # третья строка
        three_string = f"{name_string(last_name)}<<{name_string(first_name)}"

        if len(three_string) > amount_symbols:
            diff_three = amount_symbols - (len(three_string) - 30)
            text += f"{three_string[0:30]}\n" f'{three_string[30::] + "<" * diff_three}'
        else:
            diff_three = amount_symbols - len(three_string)
            text += f'{three_string + "<" * diff_three}'

        x, y = 55, 504
        go_txt.text(
            xy=(x, y),
            text=text,
            font=font_number,
            fill=(0, 0, 0, 235),
            stroke_width=0,
            anchor="lm",
        )

        txt_blur = txt_back.filter(ImageFilter.GaussianBlur(radius=0.4))
        back = Image.alpha_composite(back, txt_blur)

        """
        Сохранение полученного результата.
        """
        image_name = f"./files/es/photo_usr/{user_id}_completed"
        if size == "DOC":
            # объединяем две стороны документа
            image_doc = Image.new("RGBA", (4032, 2638), "white")
            image_doc.paste(front, (0, 0))
            image_doc.paste(back, (1016, 0))
            # Сохранение полученного результата
            image_doc.save(image_name + ".png")
            # Генерация версии в водяным знаком
            image_watermark = image_doc.copy()
            watermark = Image.open(f"./files/es/es_passport/wotermark.png")
            watermark = watermark.resize(image_doc.size).convert("RGBA")
            watermarked_image = Image.alpha_composite(image_watermark, watermark)
            watermarked_image.save(image_name + "_wm.png")
        elif size == "A4":
            # объединяем две стороны документа
            image = Image.new("RGBA", (2032, 638), "white")
            image.paste(front, (0, 0))
            image.paste(back, (1016, 0))
            # Задаем размеры A4 в миллиметрах
            width_mm = 210
            height_mm = 297
            # Задаем разрешение изображения в DPI
            resolution_dpi = 600
            # Конвертируем размеры A4 в пиксели
            width_px = int(width_mm * resolution_dpi / 25.4)
            height_px = int(height_mm * resolution_dpi / 25.4)
            # Создаем новое изображение размером A4 с белым фоном
            image_a4 = Image.new("RGBA", (width_px, height_px), "white")
            new_width = 4064  # Задаем новую ширину в пикселях
            new_height = int(
                (image.height * new_width / front.width) / 2
            )  # Вычисляем новую высоту, сохраняя соотношение сторон
            image = image.resize((new_width, new_height), Image.LANCZOS)
            image_a4.paste(image, (100, 100))
            # Версия с водяным знаком
            image_watermark = image_a4.copy()
            watermark = Image.open(f"./files/es/es_passport/wotermark.png")
            watermark = watermark.resize(image_a4.size).convert("RGBA")
            watermarked_image = Image.alpha_composite(image_watermark, watermark)
            watermarked_image.save(image_name + "_wm.png")
            # Сохраняем изображение в файл
            image_a4.save(image_name + ".png", "PNG")
        else:
            raise ValueError
        result_queue.put(image_name)
    except KeyError as _ex:
        print(_ex)
        result_queue.put(f"Error:Ошибка в предоставленных данных:\n")
    except ValueError as _ex:
        print(_ex)
        result_queue.put(f"Error:Ошибка при сохранении результата:\n")
    except Exception as _ex:
        print(_ex)
        result_queue.put(f"Error:Ошибка при генерации:\n")
